# -*- coding:UTF-8 -*-
from django.shortcuts import render
from salt_ui.salt_https_api import *
from salt_ui.salt_token_id import *
from salt_database.api_log_class import *
from salt_database.node_list_class import *
from mysite.settings import salt_api_url,auth_content
from cmdb.models import *
from cmdb.views import *
from diy_decorator.auth import *
from django.http import JsonResponse
from cmdb.base_database import *
from cmdb.mequipment.equipment_database.equipment_info_class import get_host_equipment_info,del_equipment_info
from cmdb.mequipment.equipment_database.system_info_class import del_system_info
from cmdb.mequipment.equipment_database.belong_sys_info_class import del_belong_sys_info

import re
#主机上报页面
@login_required()
def index(request):
    context = {}
    return render(request, 'saltstack/saltstack.html', context)

#主机上报
@login_required()
def assetReport(request):
    hostname = request.GET.get('hostname','')
    hostnameDeal = hostname
    if hostnameDeal != '':
        hostnameDeal = hostnameDeal.replace(".ubank365.local","")
        digitArr = re.findall(r"\d+\.?\d*",hostnameDeal)
        tmp = ''
        if digitArr:
            for i in digitArr:
                if tmp == '':
                    tmp = str(i)
                else:
                    tmp += '.' + str(i)
        hostnameDeal = tmp
    memory = request.GET.get('memory','0')
    equipment_info = {'hostname':hostname}
    test = {}
    physical_count = 0
    if hostname != '':
        tokenApiId = token_id()
        xToken={'X-Auth-Token' : tokenApiId}
        data={"client": 'local',"tgt": hostname,'fun':'grains.items'}
        s = salt_api_token(data, salt_api_url, xToken)
        test = s.run()
        if test['return'] and test['return'][0] and test['return'][0][hostname]:
            test = test['return'][0][hostname]
            equipmentType = 1
            virtual = test['virtual'].lower()
            if virtual in virtualDict:
                equipmentType = 2
            syyInnerIp = test['ipv4'][0]
            for ip in test['ipv4']:
                if ip.endswith(hostnameDeal):
                    syyInnerIp = ip
                    break
            coreVer = test['kernelrelease']
            systemVer = test['os'] + ' release ' + test['osrelease']
            hardwares = test['hwaddr_interfaces']
            hardwaresArr = {}
            for id in hardwares:
                if hardwares[id] != '00:00:00:00:00:00' and hardwares[id] != '0.0.0.0':
                    if physical_count == 0:
                        equipment_info['network_card_first'] = {'card_name':id,'mac':hardwares[id]}
                    else:
                        hardwaresArr[physical_count] = {'card_name':id,'mac':hardwares[id]}
                    physical_count += 1
            cpu = str(test['num_cpus']) + '核'
            serialNo = test['serialnumber']
            equipment_info['equipment_type'] = equipmentType
            equipment_info['sys_ip_inner'] = syyInnerIp
            equipment_info['system_ver'] = systemVer
            equipment_info['core_ver'] = coreVer
            equipment_info['network_card_list'] = hardwaresArr
            equipment_info['cpu'] = cpu
            if equipmentType == 1:
                equipment_info['serial_num'] = serialNo
            if memory == '0':
                equipment_info['memory'] = str(int(round(test['mem_total']*1.0/1000))) + 'G'
            else:
                equipment_info['memory'] = memory + 'G'
            equipment_info['cpu_model'] = test['cpu_model']
    #其他信息
    merRes = MerchantInfo.objects.all().values('id','factory_name')
    sRoomRes = ServerRoomInfo.objects.all().values('id','server_room')
    roomNoRes = RoomNoInfo.objects.all()
    roomNoDict = {}
    for singleRoomNo in roomNoRes:
        if not roomNoDict.has_key(singleRoomNo.server_room_id):
            roomNoDict[singleRoomNo.server_room_id] = []
        roomNoDict[singleRoomNo.server_room_id].append(singleRoomNo)
    firstRoomInfo = {}
    serverRoomDict = {}
    for singleRoom in sRoomRes:
        if roomNoDict.has_key(singleRoom['id']):
            singleRoom['room_no_info'] = roomNoDict[singleRoom['id']]
        if not firstRoomInfo:
            firstRoomInfo = singleRoom
        serverRoomDict[singleRoom['id']] = singleRoom
    if physical_count == 0:
        physical_count += 1
    context = {
        'merchant_info' : merRes,
        'first_room_info' : firstRoomInfo,
        'server_room_list' : serverRoomDict,
        'use_status_list' : useStatusDict,
        'equipment_type_list' : equipmentTypeDict,
        'environment_list' : environmentDict,
        'equipment_info' : equipment_info,
        'physical_count' : physical_count
    }
    # return render(request, 'saltstack/saltstack.html', {'test' : test, 'hostname':hostname})
    return render(request, 'cmdb/mequipment/equipment_add.html', context)

#主机列表
@login_required()
def nodeList(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    #列出所有已经过认证的主机列表
    context = node_list(startpage,endpage,1)
    if context['salt_key']:
        for node in context['salt_key']:
            node['status_desc'] = nodeStatusDict[node['status']]
    page_total = int(context['count']/page_num)
    if (context['count']%page_num) > 0 or page_total == 0:
        page_total += 1
    context['page_total'] = page_total
    context['page_list'] = range(1,page_total + 1)
    context['page'] = page
    context['page_num'] = page_num
    return render(request, 'saltstack/node_list.html', context)

def searchNodes(request):
    response_dict = {'status': 1}
    search = request.POST.get('search','')
    if search != '':
        response_dict['data'] = search_nodes(search)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#cmd
@login_required()
def commands(request):
    context = get_all_nodes()
    return render(request,'saltstack/salt_cmd.html',context)

def saltCmdRun(request):
    try:
        """CMD选项功能"""
        context = {}
        salt_node_name = ""
        salt_node_name_null = ""
        node_list = []
        if request.method == 'POST':
            salt_text = request.POST
            business_node = salt_text.getlist("business_node")
            for i in business_node:
                i = '%s' % (i)
                node_list.append(i.encode("utf-8"))
            salt_api_type = salt_text['comm_shell']
            #选择cmd类型执行方法
            if salt_api_type == "cmd":
                salt_cmd_lr = salt_text['salt_cmd']
                #如果使用危险命令则返回无权限
                if str(salt_cmd_lr).split()[0] in auth_content:
                    context["auth_content"] = True
                    return {'url':'saltstack/salt_cmd_run.html', 'context':context}
                #是可指定主机，注意，此权限较高
                if "salt_node_name" in salt_text:
                    if len(business_node) > 0 and len(salt_text["salt_node_name"]) > 0:
                        node_list.append(salt_text["salt_node_name"])
                    elif len(business_node) > 0 and len(salt_text["salt_node_name"]) == 0:
                        node_list = business_node
                    elif len(business_node) == 0 and len(salt_text["salt_node_name"]) > 0:
                        salt_node_name_null += salt_text["salt_node_name"]
                    elif len(salt_text["salt_node_name"]) > 0:
                        node_list = salt_text["salt_node_name"]
                    else:
                        salt_node_name_null += "*"
                else:
                    node_list = business_node
                token_api_id = token_id()
                if len(node_list) >= 2:
                    list_all = salt_api_token({'fun': 'cmd.run', 'tgt': node_list,
                                               'arg': salt_cmd_lr, 'expr_form': 'list'},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    list_all = list_all.run()
                    # time.sleep(5)
                    for i in list_all["return"]:
                        context["jid"] = i["jid"]
                        context["minions"] = i["minions"]
                        jobs_id = context["jid"]
                        jobs_url = salt_api_url + "/jobs/" + jobs_id
                        minions_list_all = salt_api_jobs(
                        jobs_url,
                        {"X-Auth-Token": token_api_id}
                        )
                        voilet_test = minions_list_all.run()
                        for i in voilet_test["return"]:
                            context["cmd_run"] = i
                            context["cmd_Advanced"] = False
                            context["salt_cmd"] = salt_text['salt_cmd']
                            context["len_node"] = len(i.keys())
                        #日志入库
                        salt_log(request.session['username'], context["minions"], int(jobs_id),
                                 salt_api_type, context["len_node"], salt_cmd_lr, context["cmd_run"])
                        return {'url':'saltstack/salt_cmd_run.html', 'context':context}
                elif len(node_list) == 1:
                    list_all = salt_api_token({'client': 'local', 'fun': 'cmd.run',
                                               'tgt': node_list, 'arg': salt_cmd_lr},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    voilet_test = list_all.run()
                    for i in voilet_test["return"]:
                        # print i.keys()
                        context["cmd_run"] = i
                        context["cmd_Advanced"] = False
                        context["salt_cmd"] = salt_text['salt_cmd']
                        context["len_node"] = len(i.keys())
                        context["minions"] = i.keys()
                    return {'url':'saltstack/salt_cmd_run.html', 'context':context}
                elif salt_node_name:
                    list_all = salt_api_token({'client': 'local', 'fun': 'cmd.run',
                                               'tgt': salt_node_name, 'arg': salt_cmd_lr},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    voilet_test = list_all.run()
                    for i in voilet_test["return"]:
                        context["cmd_run"] = i
                        context["cmd_Advanced"] = False
                        context["salt_cmd"] = salt_text['salt_cmd']
                        context["len_node"] = len(i.keys())
                        context["minions"] = i.keys()
                    #日志入库
                    salt_log(request.session['username'], context["minions"], '',
                             salt_api_type, context["len_node"], salt_cmd_lr, context["cmd_run"])
                    return {'url':'saltstack/salt_cmd_run.html', 'context':context}
                elif salt_node_name_null:
                    list_all = salt_api_token({'client': 'local', 'fun': 'cmd.run',
                                               'tgt': salt_node_name_null, 'arg': salt_cmd_lr},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    list_all = list_all.run()
                    for i in list_all["return"]:
                        context["cmd_run"] = i
                        context["cmd_Advanced"] = False
                        context["salt_cmd"] = salt_text['salt_cmd']
                        context["len_node"] = len(i.keys())
                        context["minions"] = i.keys()
                    # print yaml.dump(context["cmd_run"])
                    #日志入库
                    salt_log(request.session['username'], context["minions"], '', salt_api_type, context["len_node"], salt_cmd_lr, context["cmd_run"])
                    return {'url':'saltstack/salt_cmd_run.html', 'context':context}
                elif len(node_list) == 0:
                    context["cmd_Advanced"] = False
                    return {'url':'saltstack/salt_cmd_run.html', 'context':context}
            #如果选择类型是grains
            elif salt_api_type == "grains":
                salt_cmd_lr = salt_text['salt_cmd']
                if "salt_node_name" in salt_text:
                    if len(business_node) > 0 and len(salt_text["salt_node_name"]) > 0:
                        node_list.append(salt_text["salt_node_name"])
                    elif len(business_node) > 0 and len(salt_text["salt_node_name"]) == 0:
                        node_list = business_node
                    elif len(business_node) == 0 and len(salt_text["salt_node_name"]) > 0:
                        salt_node_name += salt_text["salt_node_name"]
                    elif len(salt_text["salt_node_name"]) > 0:
                        node_list = salt_text["salt_node_name"]
                    else:
                        salt_node_name_null += "*"
                else:
                    node_list = business_node
                token_api_id = token_id()
                if len(node_list) >= 2:
                    list_all = salt_api_token({'fun': 'grains.item', 'tgt': node_list,
                                               'arg': salt_cmd_lr, 'expr_form': 'list'},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    list_all = list_all.run()
                    for i in list_all["return"]:
                        context["jid"] = i["jid"]
                        context["minions"] = i["minions"]
                        jobs_id = context["jid"]
                        jobs_url = salt_api_url + "/jobs/" + jobs_id
                        minions_list_all = salt_api_jobs(
                        jobs_url,
                        {"X-Auth-Token": token_api_id}
                        )
                        voilet_test = minions_list_all.run()
                        for i in voilet_test["return"]:
                            context["cmd_run"] = i
                            context["cmd_Advanced"] = False
                            context["salt_cmd"] = salt_text['salt_cmd']
                            context["len_node"] = len(i.keys())
                        #日志入库
                        salt_log(request.session['username'], context["minions"], int(jobs_id),
                                 salt_api_type, context["len_node"], salt_cmd_lr, context["cmd_run"])
                        return {'url':'saltstack/salt_cmd_grains_run.html', 'context':context}
                elif len(node_list) == 1:
                    list_all = salt_api_token({'client': 'local', 'fun': 'grains.item',
                                               'tgt': node_list, 'arg': salt_cmd_lr},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    voilet_test = list_all.run()
                    for i in voilet_test["return"]:
                        # print i.keys()
                        context["cmd_run"] = i
                        context["cmd_Advanced"] = False
                        context["salt_cmd"] = salt_text['salt_cmd']
                        context["len_node"] = len(i.keys())
                        context["minions"] = i.keys()
                    #日志入库
                    salt_log(request.session['username'], context["minions"], '', salt_api_type,
                             context["len_node"], salt_cmd_lr, context["cmd_run"])
                    return {'url':'saltstack/salt_cmd_grains_run.html', 'context':context}
                elif salt_node_name:
                    list_all = salt_api_token({'client': 'local', 'fun': 'grains.item',
                                               'tgt': salt_node_name, 'arg': salt_cmd_lr},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    voilet_test = list_all.run()
                    for i in voilet_test["return"]:
                        context["cmd_run"] = i
                        context["cmd_Advanced"] = False
                        context["salt_cmd"] = salt_text['salt_cmd']
                        context["len_node"] = len(i.keys())
                        context["minions"] = i.keys()
                    #日志入库
                    salt_log(request.session['username'], context["minions"], '',
                             salt_api_type, context["len_node"], salt_cmd_lr, context["cmd_run"])
                    return {'url':'saltstack/salt_cmd_grains_run.html', 'context':context}
                elif salt_node_name_null:
                    list_all = salt_api_token({'client': 'local', 'fun': 'grains.item',
                                               'tgt': salt_node_name_null, 'arg': salt_cmd_lr},
                                              salt_api_url, {'X-Auth-Token' : token_api_id})
                    list_all = list_all.run()
                    for i in list_all["return"]:
                        context["cmd_run"] = i
                        context["cmd_Advanced"] = False
                        context["salt_cmd"] = salt_text['salt_cmd']
                        context["len_node"] = len(i.keys())
                        context["minions"] = i.keys()
                    #日志入库
                    salt_log(request.session['username'], context["minions"], '',
                             salt_api_type, context["len_node"], salt_cmd_lr, context["cmd_run"])
                    return {'url':'saltstack/salt_cmd_grains_run.html', 'context':context}
                elif len(node_list) == 0:
                    context["cmd_Advanced"] = False
                    return {'url':'saltstack/salt_cmd_grains_run.html', 'context':context}
            else:
                return {'url':'saltstack/salt_cmd_run.html', 'context':context}
    except Exception, e:
        print 'cmd run : ' , e

@login_required()
def saltCmd(request):
    result = saltCmdRun(request)
    return render(request,result['url'], result['context'])

def getSaltCmd(request):
    response_dict = {'status':1}
    salt_node_name = request.POST.get('salt_node_name')
    result=saltCmdRun(request)
    cpuSize = 0
    if result['context']['cmd_run'][salt_node_name]:
        for tmp in result['context']['cmd_run'][salt_node_name].splitlines():
            tmp=tmp.strip()
            tmpArr = tmp.split()
            if len(tmpArr) == 3:
                cpuSize += int(tmpArr[1])
    cpuSize /= 1024
    response_dict['data'] = cpuSize
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

def nodeExists(request):
    response_dict = {'status' : 1}
    minion = request.POST.get('salt_node_name')
    check = node_exists_check(minion)
    if not check:
        response_dict['status'] = 0
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

@login_required()
def saltLog(request):
    page_num=int(request.GET.get('page_num',pageNum))
    page=int(request.GET.get('page',1))
    startpage=(page-1)*page_num
    endpage=startpage+page_num
    context = salt_data_log(startpage,endpage)
    page_total = int(context['count']/page_num)
    if (context['count']%page_num) > 0 or page_total == 0:
        page_total += 1
    context['page_total'] = page_total
    context['page_list'] = range(1,page_total+1)
    context['page'] = page
    context['page_num'] = page_num
    return render(request,'saltstack/salt_logs.html', context)

def getSaltLog(request):
    response_dict = {"status":1}
    context = get_salt_log(request.POST.get('id'))
    if context:
        response_dict['data'] = context
    else:
        response_dict['status'] = 0
        response_dict['message'] = '操作失败'
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

def keyList(request):
    page_num = int(request.GET.get('page_num', pageNum))
    page = int(request.GET.get('page',1))
    startpage = (page-1) * page_num
    endpage = startpage + page_num
    nodeInfo = node_list(startpage, endpage)

    count = nodeInfo['count']
    page_total = int(count / page_num)

    keyRes = nodeInfo['salt_key']
    for node in keyRes:
            node['key_status_desc'] = keyStatusDict[node['key_status']]
    if (count%page_num) > 0 or page_total == 0:
        page_total += 1
    context = {
        'page_total' : page_total,
        'page_list' : range(1,page_total + 1),
        'page' : page,
        'page_num' : page_num,
        'salt_key_list' : nodeInfo['salt_key']
    }
    return render(request,'saltstack/key_list.html',context)

#接受key
def keyAccept(request):
    response_dict = { "status" : 1 }
    node_name = request.POST.get('node_name')
    acceptRes = ''
    try:
        acceptRes = saltKeyAccept(node_name)
        if acceptRes['return'][0]['data']['return'] and  acceptRes['return'][0]['data']['success']:
            update_salt_key_status(node_name,1)
        else:
            response_dict['status'] = 0
            response_dict['message'] = '接受key错误，请联系管理员'
    except Exception,ex:
        print Exception,ex
        response_dict['status'] = 0
        response_dict['message'] = '操作失败'

    salt_log(request.session['username'], '[\'' + node_name + '\']', '', 'salt-key', '1', 'key.accept', acceptRes)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#接受key操作
def saltKeyAccept(node_name):
    token_api_id = token_id()
    list = salt_api_token({'client': 'wheel', 'fun': 'key.accept', 'match': node_name}, salt_api_url, {"X-Auth-Token": token_api_id})
    test = list.run()
    return test


def keyDelete(request):
    response_dict = { "status" : 1 }
    node_name = request.POST.get('node_name')
    eNo = get_host_equipment_info(node_name)
    saltRes = ''
    set_transaction(False)
    try:
        saltRes = saltDeleteKey(node_name)
        cursor = get_cursor()
        delete_salt_node(node_name,cursor)
        if eNo:
            del_equipment_info(eNo, cursor)
            del_system_info(eNo, cursor)
            del_belong_sys_info(eNo, cursor)
        connection_commit()
    except Exception,ex:
        connection_rollback()
        response_dict['status'] = 0
        response_dict['message'] = '操作失败'
        print Exception,ex
    set_transaction(True)
    salt_log(request.session['username'], '[\'' + node_name + '\']', '', 'salt-key', '1', 'key.delete', saltRes)
    response=JsonResponse(response_dict,safe=False)
    response["CHARSET"]='UTF-8'
    return response

#删除key
def saltDeleteKey(node_name):
    token_api_id = token_id()
    list = salt_api_token({'client': 'wheel', 'fun': 'key.delete', 'match': node_name}, salt_api_url, {"X-Auth-Token": token_api_id})
    return list.run()


